package com.fengba.nanzhi.tabbar04.wz;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.sdk.model.BankCardParams;
import com.baidu.ocr.sdk.model.BankCardResult;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

public class AddCardActivity extends AppCompatActivity {
    private TextView add_card_sm,add_card_name,add_card_id;
    private EditText add_card_cardhome,add_card_cardid,add_card_account;
    private Button add_card_btn;
    private String user_id="",number="",user_name="";
    private ImageButton add_card_fh;

    private static final int REQUEST_CODE_BANKCARD = 111;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wz_activity_add_card);
        Token();
        Object user_info = Preferences.getParam(AddCardActivity.this,"user_info","");

        JSONObject myJson = null;

        try {
            myJson = new JSONObject(user_info.toString());
            //账号
            user_id = myJson.get("id").toString();
            number = myJson.get("idnumber").toString();
            user_name = myJson.get("realname").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //扫描银行卡按钮
        add_card_sm = findViewById(R.id.add_card_sm);
        //所属银行
        add_card_cardhome = findViewById(R.id.add_card_cardhome);
        //银行卡号
        add_card_cardid = findViewById(R.id.add_card_cardid);
        //手机号
        add_card_account = findViewById(R.id.add_card_account);
        //手机号弹出数字键盘
        add_card_account.setInputType(EditorInfo.TYPE_CLASS_PHONE);
        //确认按钮
        add_card_btn = findViewById(R.id.add_card_btn);
        //真实姓名
        add_card_name = findViewById(R.id.add_card_name);
        add_card_name.setText(user_name);
        //身份证号
        add_card_id = findViewById(R.id.add_card_id);
        add_card_id.setText(number);
        //返回
        add_card_fh = findViewById(R.id.add_card_fh);
        add_card_fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //点击扫描调用相机
        add_card_sm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tiaozhuan();
            }
        });

        //点击确认后向后天发请求;
        add_card_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = getIntent();
                String type = intent.getStringExtra("cardtype");
                if(add_card_cardid==null||add_card_cardid.getText().toString().trim().equals("")){
                    showToast(AddCardActivity.this,"请输入银行卡号");
                }else if(add_card_cardhome==null||add_card_cardhome.getText().toString().trim().equals("")){
                    showToast(AddCardActivity.this,"请输入所属银行");
                }else if(add_card_account==null||add_card_account.getText().toString().trim().equals("")){
                    showToast(AddCardActivity.this,"请输入银行预留手机号");
                }else {
                    if (type.equals("1")) {
                        String str2 = add_card_cardid.getText().toString().replaceAll(" ", "");
                        addCard(str2, user_id, add_card_account.getText().toString(), "1");
                    } else {
                        String str2 = add_card_cardid.getText().toString().replaceAll(" ", "");
                        addCard(str2, user_id, add_card_account.getText().toString(), "2");
                    }
                }
            }
        });
    }



    public void tiaozhuan(){
// 生成intent对象
        Intent intent = new Intent(AddCardActivity.this, CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_BANK_CARD);
        startActivityForResult(intent, REQUEST_CODE_BANKCARD);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            // 通过临时文件获取拍摄的图片
        String filePath = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
        BankCardParams param = new BankCardParams();
        param.setImageFile(new File(filePath));
// 调用银行卡识别服务
        OCR.getInstance().recognizeBankCard(param, new OnResultListener<BankCardResult>() {
            @Override
            public void onResult(BankCardResult result) {
                // 调用成功，返回BankCardResult对象
                add_card_cardhome.setText(result.getBankName().toString());
                add_card_cardid.setText(result.getBankCardNumber().toString());
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError对象
                showToast(AddCardActivity.this,error+"");
            }
        });
        }
    }
//获取百度云授权
    public void Token(){
        OCR.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                // 调用成功，返回AccessToken对象
                String token = result.getAccessToken();
            }
            @Override
            public void onError(OCRError error) {
                // 调用失败，返回OCRError子类SDKError对象
                showToast(AddCardActivity.this,"网络错误");
            }
        }, getApplicationContext(), "7outqMHRUg9Fjsd3RFs0PZNG", "AIbOlma4wGOchToB6bfUs3Ac41GpB6Wh");
    }

    public void addCard(String cardnumber,String user_id,String phone,String type){
        //showToast(AddCardActivity.this,"111111111111111111111111");
        OKManager.getInstance().type1009(cardnumber,user_id,phone,type, new OKManager.func4() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if(jsonObject!=null) {
                        if (jsonObject.get("code").toString().equals("0")) {
                            showToast(AddCardActivity.this, "添加成功!");
                            finish();
                        } else {
                            showToast(AddCardActivity.this, jsonObject.get("message").toString());
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String string) {
                showToast(AddCardActivity.this,"网络错误");
            }
        });
    }

    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}
